<template>
  <div class="main">
    <div class="top">
      <Row>
        <Col ref="wrapRef" v-bind="{ md: 24, lg: 14, xl: 18, xxl: 21 }">
          <ProForm
            labelAlign="right"
            ref="formRef"
            :model="formState"
            :items="items"
            :labelCol="{ span: 8 }"
            :wrapperCol="{ span: 16 }"
            :onValuesChange="onValuesChange"
            :formColLayout="formColLayout()"
          >
          </ProForm>
        </Col>
        <Col v-bind="{ md: 24, lg: 10, xl: 6, xxl: 3 }">
          <Flex justify="end">
            <b-button icon="search" @click="getInfo">统计</b-button>
          </Flex>
        </Col>
      </Row>
    </div>
    <div class="bottom" v-if="isShow">
      <div class="left">
        <div>
          <div class="title">在线率统计</div>
          <div class="head_wrapper">
            <div>
              <p>设备在线率</p>
              <span>{{ deviceData.onlineRate }}</span>
            </div>
            <div class="line"></div>
            <div>
              <p>接入总数</p>
              <span>{{ deviceData.accessNum }}</span>
            </div>
            <div>
              <p>在线数</p>
              <span>{{ deviceData.onlineNum }}</span>
            </div>
            <div>
              <p>离线数</p>
              <span>{{ deviceData.offlineNum }}</span>
            </div>
          </div>
        </div>
        <div id="bar-chart"></div>
      </div>
      <div class="right">
        <div class="right-wrapper">
          <div class="title">离线数统计</div>
        </div>
        <Table :dataSource="dataSource" :columns="columns">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'action'">
              <b-button
                type="link"
                icon="detail"
                @click="onView(record)"
                code="onLineTime:query"
                >详情</b-button
              >
            </template>
          </template>
        </Table>
      </div>
    </div>
  </div>
  <FormModal :items="_items">
    <template #details>
      <ProTable
        ref="tableRef"
        :height="400"
        hideSearch
        :fetchListApi="_getDeviceOnlineDetail"
        :columns="_columns"
      ></ProTable>
    </template>
  </FormModal>
</template>

<script lang="tsx" setup>
import { computed, nextTick, ref, shallowRef } from 'vue';
import { Col, Flex, Row, Table, TreeSelect } from 'ant-design-vue';
import * as echarts from 'echarts';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToOption, treeToArray } from '@/utils/utils';
import {
  getDeviceOnlineRateStatistics,
  getDeviceonlineRateDetail,
} from '@/api/onlineStatistics';
import { getModelInfoById } from '@/api/push';
import { reportStore } from '../store';

const {
  refreshStore,
  deviceModeOptions,
  deviceModeEnum,
  getModelOptions,
  getModelEnum,
  projectList,
} = reportStore();

const init = () => {
  refreshStore.timeDelay();
};

init();
const _items = computed<ProFormProps['items']>(() => [
  {
    label: '',
    type: 'number',
    field: 'details',
  },
]);
const _columns = computed<ProTableProps['columns']>(() => [
  {
    title: '项目名称',
    dataIndex: 'projectName',
  },
  {
    title: '设备序列号',
    dataIndex: 'code',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: {
      ...deviceModeEnum.value,
    },
  },
  {
    title: '安装位置',
    dataIndex: 'address',
  },
  {
    title: '离线时长',
    dataIndex: 'statusTime',
  },
]);

const _getDeviceOnlineDetail = async (params: any) => {
  const result: any = await getDeviceonlineRateDetail({
    codes: codes.value,
    ...params,
  });
  return result;
};

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '离线数',
    dataIndex: 'offlineNum',
    align: 'center',
    width: 220,
  },
  {
    title: '离线时长',
    dataIndex: 'offlineTime',
    align: 'center',
    width: 220,
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCodes',
    align: 'left',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 120,
    align: 'center',
  },
]);
const dataSource = ref([]);
const deviceData: any = ref({});
const formState = ref<Record<string, any>>({});
const items = computed<ProFormProps['items']>(() => [
  {
    label: '项目名称',
    type: 'input',
    field: 'projectId',
    customRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectId}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={projectList.value}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          showCheckedStrategy={TreeSelect.SHOW_ALL}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (
              omittedValues.length == treeToArray(projectList.value).length
            ) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
  {
    label: '设备类型',
    type: 'select',
    field: 'deviceType',
    props: {
      options: deviceModeOptions.value,
    },
  },
  {
    label: '设备型号',
    type: 'select',
    field: 'modelId',
    props: {
      options:
        modListOptions.value.length == 0
          ? getModelOptions.value
          : modListOptions.value,
    },
  },
]);
const column = 4;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const modListOptions = ref<Global.Option[]>([]);
const onValuesChange = async (
  params: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
  if (params.hasOwnProperty('deviceType')) {
    state.modelId = undefined;
    if (params.deviceType) {
      const res = await getModelInfoById({
        type: params.deviceType,
        modelIds: '',
      });
      modListOptions.value = listToOption(res.data, 'model', 'modelId');
    } else {
      modListOptions.value = [];
    }
  }
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 9 },
    wrapperCol: { span: 20 },
  };
});
const isShow = ref(false);
const getInfo = async () => {
  if (formState.value.projectId) {
    formState.value.projectIds = formState.value.projectId.join();
  }
  const result: any = await getDeviceOnlineRateStatistics(formState.value);
  deviceData.value = result.data;
  dataSource.value = result.data.offlineRateVOList;
  isShow.value = true;
  nextTick(() => {
    getInit(result.data);
  });
};
getInfo();
const getInit = (data: any) => {
  let dom = echarts.init(document.getElementById('bar-chart'));
  var LegData = ['在线数', '设备总数'];
  var onlineData1: any = [];
  var onlineData2: any = [];
  var XaData1: any = [];
  var XaData2: any = [];
  var yData1: any = [];
  var yData2: any = [];
  data.deviceTypeList.forEach((item: any) => {
    if (item.totalNum != 0) {
      onlineData1.push(item.onlineNum);
      XaData1.push(item.name + '\n在线率' + item.percentage);
      yData1.push(item.totalNum);
    }
  });
  data.deviceModelList.forEach((item: any) => {
    if (item.totalNum != 0) {
      onlineData2.push(item.onlineNum);
      XaData2.push(item.name + '\n在线率' + item.percentage);
      yData2.push(item.totalNum);
    }
  });
  //数据参数

  var option = {
    // title: {
    //     show: false,
    // },
    title: [
      {
        top: '5%',
        text: '类型分布',
        textStyle: {
          color: '#DCD9DB',
        },
      },
      {
        top: '51%',
        text: '型号分布',
        textStyle: {
          color: '#DCD9DB',
        },
      },
    ],
    grid: [
      {
        top: '15%',
        bottom: '60%',
      },
      {
        top: '60%',
        bottom: '8%',
      },
    ],

    legend: [
      {
        data: LegData,
        right: '15%',
        top: '5%',
        icon: 'circle',
        textStyle: {
          color: '#fff',
        },
      },
      {
        data: LegData,
        right: '15%',
        top: '50%',
        icon: 'circle',
        textStyle: {
          color: '#fff',
        },
      },
    ],
    xAxis: [
      {
        type: 'category',
        data: XaData1,
        splitLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          // rotate: 45,
          textStyle: {
            color: '#fff',
            fontSize: 14,
            lineHeight: 20,
          },
        },
        axisLine: {
          show: false,
        },
      },
      {
        gridIndex: 1,
        type: 'category',
        data: XaData2,
        splitLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          // rotate: 45,
          textStyle: {
            color: '#fff',
            fontSize: 14,
            lineHeight: 20,
          },
        },
        axisLine: {
          show: false,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          //show: false,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(255, 255, 255, .2)', //里面横着的虚线
          },
        },
        axisTick: {
          show: false,
        },
        // data: SerData,
        axisLabel: {
          textStyle: {
            color: '#fff',
            fontSize: 12,
          },
        },
        axisLine: {
          show: false,
        },
      },
      {
        gridIndex: 1,
        type: 'value',
        splitLine: {
          //show: false,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(255, 255, 255, .2)', //里面横着的虚线
          },
        },
        axisTick: {
          show: false,
        },
        // data: SerData,
        axisLabel: {
          textStyle: {
            color: '#fff',
            fontSize: 12,
          },
        },
        axisLine: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: LegData[0],
        type: 'bar',
        data: onlineData1,
        barWidth: '28px',
        itemStyle: {
          normal: {
            color: '#EBE8E8',
            // opacity: 0.8,
          },
        },
      },
      {
        name: LegData[1],
        type: 'bar',
        barGap: '-100%',
        barWidth: '28px',
        itemStyle: {
          padding: 0,
          normal: {
            color: '#998C8C',
          },
        },

        z: -10,
        data: yData1,
      },

      {
        name: LegData[0],
        type: 'bar',
        data: onlineData2,
        barWidth: '28px',
        xAxisIndex: 1,
        yAxisIndex: 1,
        itemStyle: {
          normal: {
            color: '#EBE8E8',
            // opacity: 0.8,
          },
        },
      },
      {
        name: LegData[1],
        type: 'bar',
        barGap: '-100%',
        barWidth: '28px',
        xAxisIndex: 1,
        yAxisIndex: 1,
        itemStyle: {
          padding: 0,
          normal: {
            color: '#998C8C',
          },
        },

        z: -10,
        data: yData2,
      },
    ],
    barCategoryGap: '40%',
  };
  dom.setOption(option);
  addEventListener('resize', () => {
    dom.resize();
  });
};
const codes = ref();

const { FormModal, open } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const onView = async (record: any) => {
  codes.value = record.deviceAllCodes;
  open({
    title: '详情',
    modalType: 'add',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};
</script>

<style lang="scss" scoped>
@mixin customStyle {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  margin: 10px;
}
.main {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  .top {
    padding: 20px 20px 10px;
    // display: flex;
    @include customStyle;
    .left {
      flex: 3;
    }
    .right {
      margin-left: 40px;
      flex: 2;
    }
  }
  .bottom {
    flex: 1;
    display: flex;
    .left,
    .right {
      padding: 20px 20px 10px;
      flex: 1;
      @include customStyle;
    }
    .right {
      padding: 20px 0 10px;
      .title {
        padding: 0 20px;
      }
      :deep(.ant-table) {
        background: transparent;
      }
      :deep(.ant-table-wrapper) {
        background: transparent;
        tr.ant-table-row > td {
          background: transparent !important;
        }
      }
      :deep(.ant-table-thead) {
        background: transparent !important;
        & > tr,
        & > tr > th {
          background: transparent !important;
        }
      }
    }
  }
}

#bar-chart {
  width: 100%;
  height: calc(100vh - 380px);
}

.head_wrapper {
  position: relative;
  display: flex;
  align-items: center;
  > div {
    margin-right: 80px;
    > p {
      color: #918f84;
    }
    > span {
      font-size: 24px;
      // font-weight: 800;
    }
  }
  > div:first-child {
    margin-left: 18px;
    margin-right: 89px;
    > span {
      font-size: 28px;
    }
  }
  .line {
    position: absolute;
    left: 145px;
    top: 32px;
    height: 36px;
    width: 1px;
    background-color: #f0f0f0;
  }
}
</style>
